package net.wanho.util;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

@Slf4j
public class AddressUtils {
    public static String getRealAddressById(String ip) {

        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Get请求
        HttpGet httpGet = new HttpGet("http://api.map.baidu.com/location/ip?ak=hSopadP7ih2l4c2s5piBRVmY&ip=" + ip + "&coor=bd09ll");

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                String jsonStr = EntityUtils.toString(responseEntity);
                JSONObject jsonObject = JSON.parseObject(jsonStr);

                jsonObject = JSON.parseObject((String) jsonObject.get("content"));
                if(ObjectUtil.isNotEmpty(jsonObject))
                    return (String) jsonObject.get("address");
                return "本地地址";

            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        return null;
    }
}


